import { ElMessage, ElMessageBox } from "element-plus";

let getNewTime = (type) => {
  var now = new Date();
  var year = now.getFullYear();       //年
  var month = now.getMonth() < 9 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1; //月
  var day = now.getDate() < 10 ? '0' + now.getDate() : now.getDate(); //日

  var hh = now.getHours() < 10 ? '0' + now.getHours() : now.getHours(); //时
  var mm = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes(); //分
  var ss = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds(); //秒

  switch (type) {
    case 'y':
      return `${year}`;
    case 'y-m':
      return `${year}-${month}`;
    case 'y-m-d':
      return `${year}-${month}-${day}`;
    case 'y-m-d h:m':
      return `${year}-${month}-${day} ${hh}:${mm}`;
    case 'y-m-d h:m:s':
      return `${year}-${month}-${day} ${hh}:${mm}:${ss}`;
    default:
      return `${year}-${month}-${day} ${hh}:${mm}:${ss}`;
  }
};

// 生成随机id。可选参数：id的长度
function uuid(len = 36) {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < len; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  var uuid = s.join("");
  return uuid;
}

/*
@date：表示格式化的时间；
@fmt：表示格式化的时间格式，如：yyyy-MM-dd hh:mm:ss
*/
function formatDate(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
  var o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  return fmt
}

// 客户端是否为移动端
function clientIsMobile() {
  var ua = navigator.userAgent,
    isWindowsPhone = /(?:Windows Phone)/.test(ua),
    isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
    isAndroid = /(?:Android)/.test(ua),
    isFireFox = /(?:Firefox)/.test(ua),
    isChrome = /(?:Chrome|CriOS)/.test(ua),
    isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),
    isIPhone = /(?:iPhone)/.test(ua) && !isTablet,
    isPc = !isIPhone && !isAndroid && !isSymbian;
  let os = {
    isTablet: isTablet,
    isIPhone: isIPhone,
    isAndroid: isAndroid,
    isPc: isPc
  };
  return os.isAndroid || os.isIPhone;

  if (os.isAndroid || os.isIPhone) {
    alert("手机");
  } else if (os.isTablet) {
    alert("平板");
  } else if (os.isPc) {
    alert("电脑");
  }
}

// 获取浏览器版本
function getBrowser() {
  var UserAgent = navigator.userAgent.toLowerCase();
  console.log(UserAgent);
  console.log(window.ActiveXObject);
  var browser = null;
  var browserArray = {
    IE: window.ActiveXObject || "ActiveXObject" in window, // IE
    Chrome: UserAgent.indexOf('chrome') > -1 && UserAgent.indexOf('safari') > -1, // Chrome浏览器
    Firefox: UserAgent.indexOf('firefox') > -1, // 火狐浏览器
    Opera: UserAgent.indexOf('opera') > -1, // Opera浏览器
    Safari: UserAgent.indexOf('safari') > -1 && UserAgent.indexOf('chrome') == -1, // safari浏览器
    Edge: UserAgent.indexOf('edge') > -1, // Edge浏览器
    QQBrowser: /qqbrowser/.test(UserAgent), // qq浏览器
    WeixinBrowser: /MicroMessenger/i.test(UserAgent) // 微信浏览器
  };
  console.log(browserArray)
  for (var i in browserArray) {
    if (browserArray[i]) {
      var versions = '';
      if (i == 'IE') {
        versions = UserAgent.match(/(msie\s|trident.*rv:)([\w.]+)/)[2];
      } else if (i == 'Chrome') {
        for (var mt in navigator.mimeTypes) {
          //检测是否是360浏览器(测试只有pc端的360才起作用)
          if (navigator.mimeTypes[mt]['type'] == 'application/360softmgrplugin') {
            i = '360';
          }
        }
        versions = UserAgent.match(/chrome\/([\d.]+)/)[1];
      } else if (i == 'Firefox') {
        versions = UserAgent.match(/firefox\/([\d.]+)/)[1];
      } else if (i == 'Opera') {
        versions = UserAgent.match(/opera\/([\d.]+)/)[1];
      } else if (i == 'Safari') {
        versions = UserAgent.match(/version\/([\d.]+)/)[1];
      } else if (i == 'Edge') {
        versions = UserAgent.match(/edge\/([\d.]+)/)[1];
      } else if (i == 'QQBrowser') {
        versions = UserAgent.match(/qqbrowser\/([\d.]+)/)[1];
      }
      browser = i + " " + versions;
    }
  }
  return browser;
}


function jsObj(obj) {
  return JSON.parse(JSON.stringify(obj));
}

// 手机号合法校验
function isPhoneNumber(number) {
  let abc = /^(13[0-9]|15[0|3|6|7|8|9]|18[8|9])\d{8}$/;
  return abc.test(number);
}

// dict里数组转js对象，要求格式{label: '', value: ''}
function optionToObj(list) {
  let obj = {};
  list.forEach(val => {
    obj[val.value] = val.label;
  })
  return obj;
}

// dict里数组转js对象，要求格式{label: '', value: ''}
function handleExportXls(data, fileName = '导出文件') {
  if (!data) {
    // this.$message.warning("文件下载失败")
    console.log('文件下载失败')
    return
  }
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
  } else {
    let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName + '.xls')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link); //下载完成移除元素
    window.URL.revokeObjectURL(url); //释放掉blob对象
  }
}

// 对象转字符串参数
function objToStrParams(obj) {
  let str = '';
  Object.keys(obj).forEach((key, index) => {
    let i = index == 0 ? '?' : '&';
    str += `${i}${key}=${obj[key]}`
  })
  return str;
}

/**
 * 通用防抖函数
 * fn:传入的方法
 * delay:延迟时间 毫秒 时间内再次触发刷新时间
 * **/
let timer1 = null;
function debounce(fn, delay = 300) {
  clearTimeout(timer1);
  timer1 = setTimeout(() => {
    fn();
  }, delay);
}

/**
 * 通用节流函数
 * fn:传入的方法
 * rate:时间 毫秒  规定时间内触发第一次
 * **/
let timer2 = null;
function throttle(fn, rate = 300) {
  if (timer2 == null) {
    timer2 = setTimeout(() => {
      fn()
      clearTimeout(timer2)
      timer2 = null
    }, rate)
  }
}


/**
 * 确认消息框
 * option = {msg, okText, onText, okFun, noFun, type, delay}
 *  */
function confirmBox(option = {}) {
  let {title, msg, okText, onText, okFun, noFun, type, delay, funParam} = option;
  delay = delay ? delay : 800;
  let submitTime = 0;
  ElMessageBox.confirm(msg, (title || '提示'), {
    confirmButtonText: okText || '确定',
    cancelButtonText: onText || '取消',
    type: type || 'warning',
  }).then(() => {
    let now = new Date().getTime();
    if (now - submitTime > delay) {
      submitTime = now;
      okFun && okFun(funParam);
    } else {
      okFun && okFun(funParam);
    }
  }).catch(() => {
    noFun && noFun(funParam);
  })
}

export default {
// module.exports = {     // 这个方式不能用import
  getNewTime,
  uuid,
  formatDate,
  clientIsMobile,
  jsObj,
  isPhoneNumber,
  getBrowser,
  optionToObj,
  handleExportXls,
  objToStrParams,
  debounce,
  throttle,
  confirmBox: confirmBox,
}